package io.kiki.sba.registry.server.metadata.lease.impl;

import io.kiki.sba.registry.common.model.Node;
import io.kiki.sba.registry.common.model.metaserver.Lease;
import io.kiki.sba.registry.exception.SofaRegistryMetaLeaderException;
import io.kiki.sba.registry.server.metadata.MetadataLeaderService;
import org.springframework.beans.factory.annotation.Autowired;


public class LeaderAwareLeaseManager<T extends Node> extends LeaseManager<T> {

    @Autowired
    protected MetadataLeaderService metadataLeaderService;


    @Override
    public void register(Lease<T> lease) {
        if (!amILeader()) {
            throw new SofaRegistryMetaLeaderException(metadataLeaderService.getLeader(), metadataLeaderService.getLeaderEpoch(), "leader mismatch");
        }
        super.register(lease);
    }


    @Override
    public boolean cancel(Lease<T> lease) {
        if (!amILeader()) {
            throw new SofaRegistryMetaLeaderException(metadataLeaderService.getLeader(), metadataLeaderService.getLeaderEpoch(), "leader mismatch");
        }
        return super.cancel(lease);
    }


    @Override
    public boolean renew(T renewal, int leaseDuration) {
        if (!amILeader()) {
            throw new SofaRegistryMetaLeaderException(metadataLeaderService.getLeader(), metadataLeaderService.getLeaderEpoch(), "leader mismatch");
        }
        return super.renew(renewal, leaseDuration);
    }

    protected boolean amILeader() {
        return metadataLeaderService.amILeader();
    }
}
